/*
 *  @author yangzeming
 *  @desc   常用方法扩展
 */

/*
 *  @desc  类继承
 */

/*
 *  @desc  事件分发机制
 */
var _ = _ || {};
$.extend(_,(function(){

    /**
     * 消息中心
     * @type {{eventPool: (*|jQuery|HTMLElement), observe: Function, fire: Function, stopObserving: Function}}
     */
    var MessageManager = {
        debug: false,
        eventPool: $({}),

        observe: function () {
            this.eventPool.bind.apply(this.eventPool, arguments);
        },

        fire: function () {
            this.eventPool.trigger.apply(this.eventPool, arguments);
        },

        stopObserving: function () {
            this.eventPool.unbind.apply(this.eventPool, arguments);
        }
    };

    /***
	 * @desc 用于生成类的函数
	 * @param {Object} properties 类的成员属性和方法集
	 * @return JS类对象
	 */
	var Class = function(properties){
		if(!properties.hasOwnProperty('initial') || !$.isFunction(properties.initial)){
			properties.initial = new Function();
		}
		var _getProperties = function(properties){
			var result = {
				'noMethod' : {},
				'method' : {},
				'extend' : null
			};
			for(var i in properties){
				if(i == 'prototype') continue;
				
				if($.isFunction(properties[i])){
					result.method[i] = properties[i];
				}else if($.isArray(properties[i])){
					result.noMethod[i] = Array.prototype.slice.call(properties[i], 0);
				}else if($.isPlainObject(properties[i])){
					result.noMethod[i] = $.extend({}, properties[i]);
				}else{
					result.noMethod[i] = properties[i];
				}
			}
			return result;
		};
		var _propObj = _getProperties(properties);
		var _class = function(){
			$.extend(this, _propObj.noMethod);
			if(_class.prototype.initial && $.isFunction(_class.prototype.initial)){
				_class.prototype.initial.apply(this, arguments);
			}
		};
		/***
		 * @desc 类继承方法
		 * @param {Object} prop 新类的成员属性集合
		 * @return 新的类对象
		 */
		_class.extend = function(prop){
			var _prototype = _class.prototype;
			var __prop = {};
			$.extend(__prop, _prototype, prop);
			var _newClass = Class(__prop);
			$.extend(_newClass.prototype, {
				"__parent__" : function(propName){
					var self = this;
					if(!_prototype.hasOwnProperty(propName)) return;
					return ($.isFunction(_prototype[propName])) ? function(){_prototype[propName].apply(self, arguments);} : _prototype[propName];
				},
				"__super__" : function(){
					//alert(this.parent('initial'));
					return this.__parent__('initial').apply(this, arguments);
				}
			});
			return _newClass;
		};
		if(!properties["noDispatcher"]){
			var tmp = $.extend(true,{},Dispatcher);
			$.extend(_class.prototype,tmp);
		}
		$.extend(_class.prototype, properties, {'prototype' : _class.prototype});
		
		//if()
		return _class;
	};
	/***
	 * @class 事件类
	 */
	 
	 var Event = Class({
		type : '',		//事件类型
		target : null,	//目标对象
		/**
		 * @desc 构造函数
		 * @param {String} 事件类型
		 * @param {Object} 事件目标
		 */
		initial : function(eventType, target){
			this.type = eventType;
			this.target = target;
		}
	});
	/***
	 * @class 事件分发类
	 */
	var Dispatcher = {
		_eventStack : {},
		/***
		 * @desc 绑定事件
		 * @param {String} eventType		事件类型
		 * @param {Function} eventHandler		事件处理函数
		 * @param {Object} context
		 */
		bind : function(eventType, eventHandler, context){
			if(!this._eventStack.hasOwnProperty(eventType)){
				this._eventStack[eventType] = [];
			}
			this._eventStack[eventType].push({
				'handler' : eventHandler,
				'context' : context
			});
		},
		/***
		 * @desc 绑定事件
		 * @param {String} eventType		事件类型
		 * @param {Function} eventHandler		事件处理函数
		 */
		unbind : function(eventType, eventHandler){
			if(!this._eventStack.hasOwnProperty(eventType)){
				return;
			}
			//如果没有传入具体的事件处理函数 则删除所有该eventType绑定
			if(!eventHandler || !$.isFunction(eventHandler)){
				delete this._eventStack[eventType];
				return;
			}
			var _eventStack = this._eventStack[eventType];
			for(var i = 0, len = _eventStack.length; i < len; i ++){
				if(_eventStack[i]['handler'] == eventHandler){
					_eventStack.splice(i, 1);
					break;
				}
			}
		},
		/***
		 * @desc 事件分发
		 * @param {String} eventType 事件类型
		 */
		trigger : function(eventType){
			if(!this._eventStack.hasOwnProperty(eventType) || !this._eventStack[eventType].length)
				return;
				
			var _evt = new Event(eventType, this);
			var _args = Array.prototype.slice.call(arguments, 0),
				_tempStack = [];
			_args.shift();
			_args = [_evt].concat(_args);
			
			if(this._eventStack[eventType]){
				_tempStack = Array.prototype.slice.call(this._eventStack[eventType]);
			}
			
			for(var i = 0, stack = _tempStack, len = _tempStack.length; i < len; i ++){
				if(!stack || !stack[i]){
					continue;
				}
				var obj = stack[i],
					fn = obj['handler'],
					ctx = obj['context'] || null;
				if(fn && $.isFunction(fn)){
					fn.apply(ctx, _args);
				}
			}
		},

        observe: function () {
            MessageManager.observe.apply(MessageManager, arguments);
        },

        stopObserving: function () {
            MessageManager.stopObserving.apply(MessageManager, arguments);
        },

        fire: function () {
            MessageManager.fire.apply(MessageManager, arguments);
        }
	};
	return {
		Class :Class,
		Dispatcher : Class(Dispatcher),
		MessageManager : MessageManager
	
	};
})()
);

/*
 *  @desc 工具箱 解析url 获取
 */
(function($){
	/**
     * @namespace
     */
	$.easyUtil = $.easyUtil || {};
	 /**
	* 对目标日期对象进行格式化
	* @param {String} source 目标日期对象
	* @param {String} pattern 日期格式化规则
	* @return {String} 格式化后的字符串
	*/
	$.easyUtil.dateFormat = function (source, pattern) {
	   if ('string' != typeof pattern) {
		  return source.toString(); 
		  }
	   function replacer(patternPart, result) {
		  pattern = pattern.replace(patternPart, result); 
	   }
	   var pad = function (n) { return String(n).length > 1 ? String(n) : '0' + n;}, year = source.getFullYear(), month = source.getMonth() + 1, date2 = source.getDate(), hours = source.getHours(), minutes = source.getMinutes(), seconds = source.getSeconds(); 
	   replacer(/yyyy/g, String(year));
	   replacer(/yy/g, pad(year.toString().slice(2), 2));
	   replacer(/MM/g, pad(month, 2));
	   replacer(/M/g, month);
	   replacer(/dd/g, pad(date2, 2));
	   replacer(/d/g, date2);
	   replacer(/HH/g, pad(hours, 2));
	   replacer(/H/g, hours);
	   replacer(/hh/g, pad(hours % 12, 2));
	   replacer(/h/g, hours % 12);
	   replacer(/mm/g, pad(minutes, 2));
	   replacer(/m/g, minutes);
	   replacer(/ss/g, pad(seconds, 2));
	   replacer(/s/g, seconds);
	   return pattern; 
	}; 

})(jQuery);
(function($, undefined){
    /**
     * 获取全局zIndex值,基数为10005
     * @return {Number}
     * @author yangzeming
     * @version 2012.11.19
     */
    $.getcurzIndex = function(){
        $.curzIndex = ($.curzIndex||10005);
        return $.curzIndex++;
    }
})(jQuery);
/*
 *  @desc 动画类
 */



/**
 * 获取详细的浏览器信息，核心和名字
 * @return {{core: string, name: string}}
 */
$.getBrowser = function(){
	var ua = navigator.userAgent;
	var obj = {};
	var core = '', name = '';
	if(ua.indexOf('AppleWebKit') >= 0)
		core = 'webkit';
	else if(ua.indexOf('Gecko') >= 0){
		core = 'gecko';
	}else if(ua.indexOf('MSIE') >= 0){
		core = 'ie';
	}
	if(ua.indexOf('Firefox') >= 0){
		name = 'firefox';
	}else if(ua.indexOf('360SE') >= 0){
		name = '360se';
	}else if(ua.indexOf('SE') >= 0){
		name = 'sougou';
	}else if(ua.indexOf('Maxthon') >= 0){
		name = 'maxthon';
	}else if(ua.indexOf('MSIE') >= 0){
		name = 'ie';
	}else if(ua.indexOf('Chrome') >= 0){
		name = 'chrome';
	}else if(ua.indexOf('Safari') >= 0){
		name = 'safari';
	}
	return {'core' : core, 'name' : name};
};

// 功能组件 tb.fun.js
(function ($, undefined) {

	/**
     * 回到顶部功能
	 * @namespace
	 */
	$.goTop = {
        /**
         * @default 默认配置项
         */
		defaultConfig: {
			className: 'goTop',
			positionCSS: 'bottom:20px; margin-left:489px; left:50%; position: fixed',
			scrollDelay: 400
		},
        /**
         * 初始化
         * @param config 配置项
         * @param {String} [config.className='goTop'] 配置样式
         * @param {String} [config.positionCSS='bottom:20px; margin-left:489px; left:50%; position: fixed'] 设置位置
         * @param {Number} [config.scrollDelay=400] 相应滚动时间的延迟时间
         */
		init: function (config) {
			config = $.extend({}, this.defaultConfig, config);

			this.$holder = $('<a>')
				.attr({'class': config.className, 'href': '#'})
				.css('display', 'none').bind('click.tb-gotop', this.goTop).appendTo('body');

			this.setPosition(config.positionCSS);

			this.bindScrollEvent(config.scrollDelay);

		},
		setPosition: function (css) {
			var ocss = this.css2obj(css);

			if (ocss['position'] === 'fixed' && $.browser.msie && $.browser.version < 7 ) {
				var expression;

				ocss['position'] = 'absolute';
				
				if (ocss['bottom'] && !isNaN(parseInt(ocss['bottom']))) {
					expression = 'documentElement.scrollTop+documentElement.clientHeight - this.offsetHeight - ' + parseInt(ocss['bottom']);			
				} else {
					expression = 'documentElement.scrollTop + ' + (isNaN(parseInt(ocss['top'])) ? 'documentElement.scrollTop+documentElement.clientHeight - this.offsetHeight' : parseInt(ocss['top']));		
				
				}
				
				ocss['bottom'] = 'auto';
				delete ocss['top'];

				this.$holder[0].style.setExpression('top', expression);

				$('html').css('background', 'url(about:blank) fixed');
			}
			
			this.$holder.css(ocss);
			
		},
		rPositionName: /^(?:left|right|bottom|top|position|margin(?:-left|right|bottom|top)?)$/,
		css2obj: function (css) {
			var r = this.rPositionName,
				p = css.toLowerCase().split(';'),
				o = {},
				key, value;

			for (var i = 0, j = p.length; i < j; i++) {
				var tmp = p[i];
				if ((tmp = $.trim(tmp)) === '') {
					continue;
				}
				key = $.trim(tmp.substring(0, tmp.indexOf(':')));
				value = $.trim(tmp.substring(tmp.indexOf(':')+1));

				if (key === '' || value === '' || !r.test(key)) {
					continue;
				}

				o[key] = value;
			}

			return o;
		},
		isShow: false,
		bindScrollEvent: function (scrollDelay) {
			var timer,
				self =this;

			$(window).bind('scroll.tb-gotop', function () {
				clearTimeout(timer);
				timer = setTimeout(function () {
					if ($(window).scrollTop() > 0) {
						if (!self.isShow) {
							self.$holder.fadeIn();
							self.isShow = true;
						}	
					} else {
						if (self.isShow) {
							self.$holder.fadeOut();
							self.isShow = false;
						}			
					}
				}, scrollDelay);
			});
		},
		goTop: function () {
			var timer;
			var top = $(window).scrollTop(),
				left = $(window).scrollLeft();

			if($.browser.msie){
				window.scrollTo(left,0);
			}else{
				function setScroll(){
					top = Math.floor(top / 2);
					window.scrollTo(left, top);
					 if(top>2){
						scrollTimer = setTimeout(setScroll,40);
					}else{
						window.scrollTo(left,0);
						clearTimeout(scrollTimer);
					}
				}
				setScroll();
			}
			return false;
		}
	};


})(jQuery);